import React, {useEffect, useState} from 'react';
import {PageContainer} from '@ant-design/pro-layout';
import {Button, Card, DatePicker, Form, Input, message, Select, Tag, Tooltip} from 'antd';
import ProTable from '@ant-design/pro-table';
import HttpRequest from "@/utils/HttpRequest";
import {defaultDomain} from "@/config/domain";
import moment from 'moment'
import ReactJson from 'react-json-view'
import onCopy, {FormatDateTime, ToStringByte} from "@/utils/DateTime";
import {MessageDetail} from "@/pages/message/MessageDetail";

const { RangePicker } = DatePicker

const Message: React.FC = () => {
  const [hideMe, setHideMe] = useState('')
  const [msgHide, setMsgHide] = useState('none')
  const [msgLabel, setMsgLabel] = useState('Message Key')
  const [keyRequire, setKeyRequire] = useState(false)
  const [timeRequire, setTimeRequire] = useState(true)
  const [dataSource, setDataSource] = useState([])
  const [selectedTopics, setSelectedTopics] = useState('')
  const [loading, setLoading] = useState(false)
  const [options, setOptions] = useState([])

  const searchByTopic = 1
  const searchByMsgId = 2
  const searchByKey = 3

  // @ts-ignore
  useEffect(async () => {
    const res = await HttpRequest({
      baseURL: defaultDomain,
      url: '/topic/list.query',
      method: 'GET',
      params: {},
    })
    console.log('res=', res)
    // @ts-ignore
    const data = res.data
    const itemList = data?.topicList
    // @ts-ignore
    const dList = []
    if (itemList) {
      for (const i in itemList) {
        let d = itemList[i]
        if (!d.startsWith('%')) {
          dList.push(itemList[i])
        }
      }
    }

    const opList: ((prevState: never[]) => never[]) | { value: any; label: any; }[] = []
    dList.map((item) => {
      opList.push({
        value: item,
        label: item,
      })
    })
    // @ts-ignore
    setOptions(opList)
    console.log('options>', opList)
  }, [])

  function doSelect(v: any) {
    console.log('vvv=', v)
    if (v == searchByTopic) {
      setHideMe('')
      setMsgHide('none')
      setTimeRequire(true)
      setKeyRequire(false)
    } else {
      setMsgHide('')
      setHideMe('none')
      setTimeRequire(false)
      setKeyRequire(true)
      if (v == searchByKey) {
        setMsgLabel('Message Key')
      } else if (v == searchByMsgId) {
        setMsgLabel('Message ID')
      }
    }
  }

  function bindProp(record: {
    isJson: boolean
    messageBody: any
    properties: any
    proList: any
  }) {
    let p = record.properties
    const dataList = []
    if (p) {
      for (const i in p) {
        console.log(i, p[i])
        dataList.push({ key: i, value: p[i] })
      }
    }

    try {
      record.messageBody = JSON.parse(record.messageBody)
      record.isJson = true
    } catch (e) {
      record.isJson = false
      record.messageBody = { '>': JSON.stringify(record.messageBody) }
      record.proList = dataList
    }
  }

  function getSearchTopicValue(v: any) {
    setSelectedTopics(v)
  }

  async function doSearch(v: any) {
    let searchType = v.searchType
    let topic = v.topic
    let messageKey = v.messageKey
    let timeRange = v.timeRange
    let url = ''
    if (searchType == searchByKey) {
      url =
        '/message/queryMessageByTopicAndKey.query?key=' +
        messageKey +
        '&topic=' +
        topic
    } else if (searchType == searchByMsgId) {
      url = '/message/viewMessage.query?msgId=' + messageKey + '&topic=' + topic
    } else if (searchType == searchByTopic) {
      let begin = timeRange[0].valueOf()
      let end = timeRange[1].valueOf()
      url =
        '/message/queryMessageByTopic.query?begin=' +
        begin +
        '&end=' +
        end +
        '&topic=' +
        topic
    }

    const res = await HttpRequest({
      baseURL: defaultDomain,
      url: url,
      method: 'GET',
      params: {},
    })
    console.log('res=', res)
    // @ts-ignore
    const status = res.status
    let dataList = []
    if (status === 0) {
      if (searchType == searchByMsgId || searchType == searchByKey) {
        const messageView = res.data.messageView
        if (messageView) {
          messageView.strProp = JSON.stringify(messageView.properties)
          bindProp(messageView)
          dataList.push(messageView)
        }
      } else {
        const resData = res.data
        if (resData) {
          for (const i in resData) {
            const messageView = resData[i]
            messageView.strProp = JSON.stringify(messageView.properties)
            dataList.push(messageView)
          }
        }
      }
      // @ts-ignore
      setDataSource(dataList)
      console.log('>>>', dataList)
      if (dataList && dataList.length <= 0) {
        message.info('暂时没有数据')
      }
    } else {
      message.error('查询不到数据')
      setDataSource([])
    }
  }

  async function getMessage(messageKey: string, record: { bornTimestamp?: number; messageBody?: any; isJson?: any; }) {
    setLoading(true)
    // @ts-ignore
    let url =
      '/message/viewMessage.query?msgId=' +
      messageKey +
      '&topic=' +
      selectedTopics
    const res = await HttpRequest({
      baseURL: defaultDomain,
      url: url,
      method: 'GET',
      params: {},
    })

    console.log('res=', res)
    // @ts-ignore
    const status = res.status
    if (status === 0) {
      const resData = res.data
      if (resData) {
        const messageView = resData.messageView
        console.log('messageView', messageView)
        try {
          record.messageBody = JSON.parse(messageView.messageBody)
          record.isJson = true
        } catch (e) {
          record.isJson = false
          record.messageBody = { '>': JSON.stringify(messageView.messageBody) }
        }
      }
    }

    setLoading(false)
  }
  return (
    <PageContainer>
      <Card>
        <Form
          name="wrap"
          labelCol={{ flex: '110px' }}
          labelAlign="left"
          wrapperCol={{ flex: 1 }}
          colon={false}
          onFinish={doSearch}
        >
          <Input.Group compact>
            <Form.Item
              label="查询方式："
              name="searchType"
              initialValue={['1']}
              rules={[{ required: true }]}
              style={{ display: 'inline-block', width: 'calc(20% - 8px)' }}
            >
              <Select onChange={doSelect}>
                <Select.Option value="1">按照Topic查询</Select.Option>
                <Select.Option value="2">按照Message Id查询</Select.Option>
                <Select.Option value="3">按照Message Key查询</Select.Option>
              </Select>
            </Form.Item>

            <Form.Item
              label="Topic"
              name="topic"
              rules={[{ required: true }]}
              style={{
                display: 'inline-block',
                width: 'calc(30% - 8px)',
                marginLeft: '10px',
              }}
            >
              <Select
                showArrow
                showSearch={true}
                onSelect={getSearchTopicValue}
                allowClear={true}
                options={options}
              ></Select>
            </Form.Item>

            <Form.Item
              label={msgLabel}
              name="messageKey"
              rules={[{ required: keyRequire }]}
              style={{
                display: msgHide,
                width: 'calc(35% - 8px)',
                marginLeft: '10px',
              }}
            >
              <Input />
            </Form.Item>

            <Form.Item
              label="时间范围"
              name="timeRange"
              rules={[{ required: timeRequire }]}
              style={{
                display: hideMe,
                width: 'calc(30% - 8px)',
                marginLeft: '10px',
              }}
            >
              <RangePicker
                ranges={{
                  //startDate: moment().startOf('day').subtract(6, 'days')
                  '1分钟': [
                    moment().startOf('minute').subtract(1, 'minutes'),
                    moment(),
                  ],
                  '2分钟': [
                    moment().startOf('minute').subtract(2, 'minutes'),
                    moment(),
                  ],
                  '3分钟': [
                    moment().startOf('minute').subtract(3, 'minutes'),
                    moment(),
                  ],
                  '5分钟': [
                    moment().startOf('minute').subtract(5, 'minutes'),
                    moment(),
                  ],
                  '10分钟': [
                    moment().startOf('minute').subtract(10, 'minutes'),
                    moment(),
                  ],
                  '15分钟': [
                    moment().startOf('minute').subtract(15, 'minutes'),
                    moment(),
                  ],
                  '30分钟': [
                    moment().startOf('minute').subtract(30, 'minutes'),
                    moment(),
                  ],
                  '1小时': [
                    moment().startOf('minute').subtract(60, 'minutes'),
                    moment(),
                  ],
                  '2小时': [
                    moment().startOf('minute').subtract(120, 'minutes'),
                    moment(),
                  ],
                  '3小时': [
                    moment().startOf('minute').subtract(180, 'minutes'),
                    moment(),
                  ],
                  '5小时': [
                    moment().startOf('minute').subtract(300, 'minutes'),
                    moment(),
                  ],
                  '8小时': [
                    moment().startOf('minute').subtract(480, 'minutes'),
                    moment(),
                  ],
                  '10小时': [
                    moment().startOf('minute').subtract(600, 'minutes'),
                    moment(),
                  ],
                  '12小时': [
                    moment().startOf('minute').subtract(720, 'minutes'),
                    moment(),
                  ],
                  '1天': [
                    moment().startOf('day').subtract(1, 'days'),
                    moment(),
                  ],
                  '2天': [
                    moment().startOf('day').subtract(2, 'days'),
                    moment(),
                  ],
                  '3天': [
                    moment().startOf('day').subtract(3, 'days'),
                    moment(),
                  ],
                  '5天': [
                    moment().startOf('day').subtract(5, 'days'),
                    moment(),
                  ],
                  '7天': [
                    moment().startOf('day').subtract(7, 'days'),
                    moment(),
                  ],
                  '10天': [
                    moment().startOf('day').subtract(10, 'days'),
                    moment(),
                  ],
                  '15天': [
                    moment().startOf('day').subtract(15, 'days'),
                    moment(),
                  ],
                  '30天': [
                    moment().startOf('day').subtract(30, 'days'),
                    moment(),
                  ],
                  '45天': [
                    moment().startOf('day').subtract(45, 'days'),
                    moment(),
                  ],
                }}
                showTime={{
                  hideDisabledOptions: true,
                  defaultValue: [
                    moment('00:00:00', 'HH:mm:ss'),
                    moment('11:59:59', 'HH:mm:ss'),
                  ],
                }}
                format="YYYY-MM-DD HH:mm:ss"
              />
            </Form.Item>

            <Form.Item label="  " style={{ marginLeft: '10px' }}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
            </Form.Item>
          </Input.Group>
          <Form.Item>
            <ProTable
              rowKey="msgId"
              key={'msgId'}
              dataSource={dataSource}
              search={false}
              pagination={{ pageSize: 20 }}
              toolBarRender={false}
              loading={loading}
              // @ts-ignore
              columns={[
                {
                  title: '消息ID',
                  align: 'center',
                  width: '30%',
                  dataIndex: 'msgId',
                  key: 'messageId',
                  render: (text, record) => (
                    <div
                      style={{
                        wordWrap: 'break-word',
                        wordBreak: 'break-word',
                      }}
                      onDoubleClick={() => {
                        onCopy(text, '消息ID')
                      }}
                    >
                      {text}
                    </div>
                  ),
                },
                {
                  title: '发送端地址',
                  align: 'center',
                  dataIndex: 'bornHost',
                  key: 'bornHost',
                },
                {
                  title: '发送时间',
                  align: 'center',
                  dataIndex: 'bornTimestamp',
                  key: 'bornTimestamp',
                  render: (dom: any, record: { bornTimestamp: number }) => (
                    <div>{FormatDateTime(record.bornTimestamp / 1000)}</div>
                  ),
                },
                {
                  title: '重试次数',
                  align: 'center',
                  dataIndex: 'reconsumeTimes',
                  key: 'reconsumeTimes',
                },
                {
                  title: '消息大小',
                  align: 'center',
                  dataIndex: 'storeSize',
                  key: 'storeSize',
                  render: (text, record) => {
                    // @ts-ignore
                    return ToStringByte(record.storeSize)
                  },
                },
                {
                  title: '消息类型',
                  align: 'center',
                  dataIndex: 'strProp',
                  key: 'properties',
                  render: (text, record) => {
                    // @ts-ignore
                    let tms = record.properties['__STARTDELIVERTIME']
                    let color = 'green'
                    let msgType = '普通'
                    let infoMsg = ''
                    if (tms) {
                      let t = Number.parseInt(tms)
                      msgType = '延迟'
                      color = '#FAA219'
                      infoMsg = '延迟发送时间:' + FormatDateTime(t / 1000)
                    }

                    return (
                      <Tooltip title={infoMsg}>
                        <Tag
                          title={msgType}
                          color={color}
                          style={{
                            cursor: 'pointer',
                            wordWrap: 'break-word',
                            wordBreak: 'break-word',
                          }}
                        >
                          {msgType}
                        </Tag>
                      </Tooltip>
                    )
                  },
                },
                {
                  title: '消息内容',
                  align: 'center',
                  dataIndex: 'messageBody',
                  key: 'messageBody',
                  hideInTable: true,
                  width: '0%',
                  render(text, record) {
                    // @ts-ignore
                    if (!record.messageBody || record.messageBody == '') {
                      return (
                        <div style={{cursor: 'pointer', marginLeft: '20px'}}>
                          <Tag
                            color="green"
                            onClick={() => {
                              // @ts-ignore
                              getMessage(record.msgId, record)
                            }}
                          >
                            获取消息
                          </Tag>
                        </div>
                      )
                    } else {
                      // @ts-ignore
                      // @ts-ignore
                      return (
                        <div
                          style={{
                            wordWrap: 'break-word',
                            wordBreak: 'break-word',
                            textAlign: 'left',
                          }}
                        >
                          <span
                            onDoubleClick={() => {
                              onCopy(
                                // @ts-ignore
                                JSON.stringify(record.messageBody),
                                '消息内容'
                              )
                            }}
                          >
                            <ReactJson
                              iconStyle="triangle"
                              collapsed={true}
                              theme="summerfruit:inverted"
                              displayDataTypes={false}
                              displayObjectSize={false}
                              // @ts-ignore
                              src={record.messageBody}
                            />
                          </span>
                        </div>
                      )
                    }
                  },
                },
                {
                  title: '操作',
                  align: 'center',
                  dataIndex: 'detail',
                  key: 'detail',
                  render: (dom, record) => {
                    return [
                      //  @ts-ignore
                      <MessageDetail key={'messageDetail'} record={record} />,
                    ]
                  },
                },
              ]}
            />
          </Form.Item>
        </Form>
      </Card>
    </PageContainer>
  )
}
export default Message
